import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { Toast } from 'antd-mobile';
import {countTotalNum} from '../../store/actionCreator'

class ProductFooter extends Component {
  render() {
    return (
      <div className='ProductFooter'>
        <div className="ProductFooterLt">
          {this.props.productInfo.showSkuSpecList ? <i onClick={() => {
            this.props.changeShowSkuSpecList(false)
          }}>返回</i> : <span></span>}
        </div>
        <div className="ProductFooterMid">
          立即购买
        </div>
        <div className="ProductFooterRt" onClick={() => {
          if (!this.props.productInfo.showSkuSpecList) {
            this.props.changeShowSkuSpecList(true)
          } else {
            Toast.info('加入成功', 1);
            let arr = [...this.props.CartList]
            var isNew = true
            for (let i = 0; i < arr.length; i++) {
              if (JSON.stringify(arr[i].SkuSpecList) === JSON.stringify(this.props.productInfo.SkuSpecList)) {

                arr[i].num += this.props.productInfo.num
                isNew = false
                break;
              }
            }
            let CartList=[];
            if (isNew) {
              let newGoods=JSON.parse(JSON.stringify(this.props.productInfo))
              newGoods.id=Date.now()
              CartList=[...arr,newGoods]
            } else {
              CartList=[...arr]
            }
            this.props.countTotal(CartList)
            this.props.changeProductReducer(['CartList'], CartList)
          }
        }}>
          加入购物车
        </div>
      </div>
    )
  }
}
const mapStateToProps = ((state) => {
  return {
    CartList: state.getIn(['productReducer', 'CartList']),
    productInfo: state.getIn(['productReducer', 'productInfo'])
  }
})
const mapDispatchToProps = (dispatch) => {
  return {
    changeShowSkuSpecList: (bool) => {
      let action = (bool) => {
        return {
          type: 'CHANGE_SHOW',
          payload: bool
        }
      }
      dispatch(action(bool))
    },
    changeProductReducer: (arr, val) => {
      let action = (arr, val) => {
        return {
          type: 'UPDATE_PRODUCT_DETAIL',
          payload: {
            keyArr: arr,
            val: val
          }
        }
      }
      dispatch(action(arr, val))
    },
    /* 加入购物车开始*/
    addToCartList: (info) => {
      console.log(info);
    },
    /* 加入购物车结束 */
     /* 计算购物总数开始 */
     countTotal:(arr)=>{
      var num=0
      arr.forEach(v=>{
        num+=v.num
      })
      dispatch(countTotalNum(num))
    }

    /* 计算购物总数结束 */

  }
}
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ProductFooter))

